/*
1、关联测算/报价的按钮关联问题：
    1）当业务机会中的执行公司类型为迈克时，可以关联 合同中对方主体ID=业务机会中的客户名ID的有效的测算/报价；

    2）当业务机会中的执行公司类型非迈克时，可以关联 合同中对方主体ID=业务机会中的执行公司ID的有效的测算/报价；
*/
public with sharing class ContractLinkOppController {
    public List<QuoteMeasureBean> qmbList { get; set; }

    public String conId { get; private set; }
    public Contract__c con { get; set; }
	public Boolean isTerminalContract {get;set;}
    public List<SelectOption> opts {get;set;}
    public Boolean isShouldLink {get;set;}
    public String msg {get;set;}///结果
    public Boolean isSuccess {get;set;}//是否成功
    
    public ContractLinkOppController(ApexPages.StandardController stdController) {
        qmbList = new List<QuoteMeasureBean>();
        conId = System.currentPageReference().getParameters().get('conid');
        opts = new List<SelectOption>();
        opts.add(new SelectOption('', System.Label.Option_None));
        opts.add(new SelectOption('是', '试剂和仪器一起关联'));
        opts.add(new SelectOption('否', '只关联仪器'));
        msg = '';



    }

    public void init() {
        con = [select Name,Status__c,RecordType.DeveloperName, TerminalCustomer__c,Account__c ,Account__r.RecordType.DeveloperName from Contract__c where Id = :conId];
        isTerminalContract = con.RecordType.DeveloperName == 'TerminalContract';
        isShouldLink = (con.Status__c == '审批中' || con.Status__c == '已生效') ? false : true;
        if (!isShouldLink){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '合同已生效或者审批中不能关联!'));
            return;
        }
        search();
    }

    public void save() {
        Savepoint sp = Database.setSavepoint();
        try {
            // 必须选择了报价/测算才能保存
            List<QuoteMeasureBean> selectedList = new List<QuoteMeasureBean>();
            Set<Id> oppIds = new Set<Id>();
            for (QuoteMeasureBean qmb : qmbList) {
            if (qmb.chk == true) {
                    selectedList.add(qmb);
                }
            }
            if (selectedList.size() == 0) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '请选择报价/测算'));
                return ;
            }
            // 合同产品delete
            List<ContractProduct__c> delList = [select Id from ContractProduct__c where Contract__c = :conId];
            if (delList.size() > 0) delete delList;

            // 拿到选定数据的报价/测算Id
            Set<Id> quoteIds = new Set<Id>();
            Map<Id,String> measureIds = new Map<Id,String>();

            List<Measure_Calculate__c>  mcList= new List<Measure_Calculate__c>();
            // 最后要把报价和合同关联起来，拿到需要关联的报价Id
            Set<Id> finalQIds = new Set<Id>();
            for (QuoteMeasureBean qmb : selectedList) {
                if (qmb.q != null) {
                    quoteIds.add(qmb.q.Id);
                    finalQIds.add(qmb.q.Id);
                }
                if (qmb.mc != null) {
                    if (String.isBlank(qmb.isAppendRegent) == true) {///是否关联试剂必填
                         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '是否关联试剂产品必填!'));
                        return  ;
                    }
                    measureIds.put(qmb.mc.Id,qmb.isAppendRegent);
                    mcList.add(new Measure_Calculate__c(Id=qmb.mc.Id,WhetherToSignContract__c =qmb.isAppendRegent));
                }
            }

          ///合同产品记录类型 
            Id rtYiqi = Utils.getRecordTypeIdByDevNameAndObjName('InstrumentContractProduct','ContractProduct__c');
            Id rtShiji = Utils.getRecordTypeIdByDevNameAndObjName('ReagentContractProduct','ContractProduct__c');


            // 合同产品insert
            List<ContractProduct__c> insList = new List<ContractProduct__c>();
            //用于检测是否存在重复的产品 ,如果存在则报错
            Map<Id ,String> duplicateProduct = new Map<Id,String>();
            List<Quote> qlist = new List<Quote>();
            // List<Measure_Calculate__c> mclist = new List<Measure_Calculate__c>();
             // 检索测算下面所有的测算产品
            if (measureIds.size() > 0) {
                for (Measure_Calculate_Product__c mcp : [select Id,  Product__c, Product__r.Name, Measure_Calculate__r.Opportunity__c 
                    ,WarrantyPeriod__c,ChargingStandard__c,ResponseHours__c,Period__c,ApplicationTrainin__c,EquipmentCheck__c,
                    Product__r.Brand__c,Product__r.Spec__c,Product__r.SerialNo__c,CoopType__c,
                    EquipmentCheckGoods__c,CheckPeriod__c,Consumables__c,RapidWear__c,SpecialRequirement__c,DealerInstCost__c,
                    SalesPriceWT__c,SalesPriceManager__c,Product__r.Category0__c,Measure_Calculate__c,Quantity__c
                    from Measure_Calculate_Product__c where Measure_Calculate__c in : measureIds.keySet()]) {


                   if(!duplicateProduct.containsKey(mcp.Product__c)){
                        duplicateProduct.put(mcp.Product__c,'');
                        //如果没有勾选试剂关联 跳过 试剂
                        if (measureIds.get(mcp.Measure_Calculate__c) == '否' && mcp.Product__r.Category0__c != '仪器') {
                            continue;
                        }
                         insList.add(
                        new ContractProduct__c(
                            Name = mcp.Product__r.Name, 
                            Product__c = mcp.Product__c,
                            Measure_Calculate_Product__c = mcp.Id,
                            Contract__c = conId,
                            Opportunity__c = mcp.Measure_Calculate__r.Opportunity__c,
                            Quantity__c = mcp.Quantity__c,
                            ///保修条款
                            WarrantyPeriod__c = mcp.WarrantyPeriod__c,
                            ChargingStandard__c = mcp.ChargingStandard__c,
                            ResponseHours__c = mcp.ResponseHours__c,
                            Period__c = mcp.Period__c,
                            ApplicationTraining__c = mcp.ApplicationTrainin__c, 
                            EquipmentCheck__c = mcp.EquipmentCheck__c,
                            EquipmentCheckGoods__c = mcp.EquipmentCheckGoods__c,
                            CheckPeriod__c= mcp.CheckPeriod__c,
                            Consumables__c = mcp.Consumables__c,
                            RapidWear__c = mcp.RapidWear__c,
                            SpecialRequirement__c = mcp.SpecialRequirement__c,
                            ///价格
                            SalesPrice__c = con.Account__r.RecordType.DeveloperName == 'Dealer' ?mcp.DealerInstCost__c : mcp.SalesPriceWT__c,
                            ManagerSalesPrice__c = mcp.SalesPriceManager__c,
                            RecordTypeId = mcp.Product__r.Category0__c == '仪器' ? rtYiqi:rtShiji,
                            CoopType__c = mcp.CoopType__c


                        )
                    );
                   }else{
                    msg += mcp.Product__r.Brand__c +'-'+ mcp.Product__r.Name +'-' +mcp.Product__r.Spec__c+'*'+mcp.Product__r.SerialNo__c + ';\r\n';

                       continue;
                   }
                   
                }
            }
            // 检索报价下面所有的报价产品
            if (quoteIds.size() > 0) {
                for (QuoteProduct__c qp : [select Id, Name, Product__c,Product__r.Name, Quote__c, Quote__r.OpportunityId,WarrantyPeriod__c,ChargingStandard__c,ResponseHours__c,Period__c,ApplicationTraining__c
                                           ,EquipmentCheck__c,EquipmentCheckGoods__c,CheckPeriod__c,Consumables__c,RapidWear__c,Remarks__c
                                           ,Product__r.Brand__c,Product__r.Spec__c,Product__r.SerialNo__c,CoopType__c,WhetherImplementPolicyPrice__c
                                           ,SpecialRequirement__c,UnitPrice__c,Product__r.Category0__c,Quantity__c,SalesPrice__c
                                           from QuoteProduct__c where Quote__c in : quoteIds]) {
                   if(!duplicateProduct.containsKey(qp.Product__c)){//如果不存在 
                   duplicateProduct.put(qp.Product__c,'');
                   }else{
                            msg += qp.Product__r.Brand__c +'-'+ qp.Product__r.Name +'-' +qp.Product__r.Spec__c+'*'+qp.Product__r.SerialNo__c + ';\r\n';
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'产品:' +qp.Product__r.Name+'.已经存在!'));
                       //存在  报错
                       // return null;
                       continue;
                   }
                    insList.add(
                        new ContractProduct__c(
                            Name = qp.Name,
                            Product__c = qp.Product__c,
                            QuoteProduct__c = qp.Id,
                            Contract__c = conId,
                            Opportunity__c = qp.Quote__r.OpportunityId,
                            Quantity__c = qp.Quantity__c,
                         //添加 6.30  
                        WarrantyPeriod__c = qp.WarrantyPeriod__c,
                        ChargingStandard__c = qp.ChargingStandard__c,
                        ResponseHours__c = qp.ResponseHours__c,
                        Period__c = qp.Period__c,
                        ApplicationTraining__c = qp.ApplicationTraining__c, 
                        EquipmentCheck__c = qp.EquipmentCheck__c,
                        EquipmentCheckGoods__c = qp.EquipmentCheckGoods__c,
                        CheckPeriod__c= qp.CheckPeriod__c,
                        Consumables__c = qp.Consumables__c,
                        RapidWear__c = qp.RapidWear__c,
                        SpecialRequirement__c = qp.SpecialRequirement__c,
                        SalesPrice__c = qp.SalesPrice__c,
                        RecordTypeId = qp.Product__r.Category0__c == '仪器' ? rtYiqi:rtShiji,
                        Remarks__c = qp.Remarks__c,
                        WhetherImplementPolicyPrice__c = qp.WhetherImplementPolicyPrice__c,
                        CoopType__c = qp.CoopType__c

                        )
                    );
                }
            }
           
            insert insList;

            // 更新报价
            for (Id qid : finalQIds) {
                qlist.add(
                    new Quote(
                        Id = qid,
                        Contract__c = conId
                    )
                );
            }
            // update qlist;
            if(qlist.size() > 0)ControllerUtil.updateQuoteList(qlist);
            if (mcList.size() > 0) ControllerUtil.updateMCList(mcList);
            msg = msg.length() > 0 ? '关联成功'+insList.size()+'条合同产品!下列报价产品已经存在合同中:'+msg  : '关联成功'+insList.size()+'条合同产品!';
           isSuccess = true;
        } catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
        }
        
    }

    public void search() {

        String sql = 'select Id, Name, Type__c, LastModifiedDate, Contract__c, Contract__r.Name from Quote where IsActive__c = true and ActiveMeasure__c = null and ( Contract__c = null or Contract__r.Status__c != \'已生效\' or  Contract__r.Stopped__c = true )and Opportunity.WinRatio__c != null   and Opportunity.StageName = \'招标\' ';
        if(con.TerminalCustomer__c == null ){
           sql += ' and ((Opportunity.ExecutiveCompany__r.RecordType.DeveloperName =\'Maccura\' and Opportunity.AccountId =\''+con.Account__c+'\' )or(Opportunity.ExecutiveCompany__r.RecordType.DeveloperName !=\'Maccura\' and Opportunity.ExecutiveCompany__c =\''+con.Account__c+'\'))'; 
        }else{
           sql += ' and ((Opportunity.ExecutiveCompany__r.RecordType.DeveloperName =\'Maccura\' and Opportunity.AccountId =\''+con.Account__c+'\' )or(Opportunity.ExecutiveCompany__r.RecordType.DeveloperName !=\'Maccura\' and Opportunity.ExecutiveCompany__c =\''+con.Account__c+'\')) and Opportunity.AccountId = \''+con.TerminalCustomer__c+'\''; 

        }                 
          List<Quote> qlist = Database.query(sql);                   
          for (Quote q : qlist) {
            qmbList.add(new QuoteMeasureBean(q, conId));
        }
     /*
        // 检索报价，自身有效且没有有效测算，同时业务机会阶段为招标且有赢单率小组
       if(con.HasContract__c == '无合同'){
              List<Quote> qlist = [select Id, Name, Type__c, HasContract__c, LastModifiedDate, Contract__c, Contract__r.Name from Quote where 
                             IsActive__c = true and ActiveMeasure__c = null and ( Contract__c = null or Contract__r.Status__c != '已生效' or  Contract__r.Stopped__c = true )
                            and Opportunity.WinRatio__c != null   and Opportunity.StageName = '招标' and  ((Type__c = '试剂报价' and HasContract__c = '无合同') or Type__c = '仪器报价')
                            and ((Opportunity.ExecutiveCompany__r.RecordType.DeveloperName ='Maccura' and Opportunity.AccountId =:con.Account__c )or(Opportunity.ExecutiveCompany__r.RecordType.DeveloperName !='Maccura' and Opportunity.ExecutiveCompany__c =:con.Account__c) ) ];
        for (Quote q : qlist) {
            qmbList.add(new QuoteMeasureBean(q, conId));
        }
       }else{
             List<Quote> qlist = [select Id, Name, Type__c, HasContract__c, LastModifiedDate, Contract__c, Contract__r.Name from Quote where 
                             IsActive__c = true and ActiveMeasure__c = null and ( Contract__c = null or Contract__r.Status__c != '已生效' or  Contract__r.Stopped__c = true  ) 
                              and Opportunity.StageName = '招标'  and Opportunity.WinRatio__c != null and 
                            ((Opportunity.ExecutiveCompany__r.RecordType.DeveloperName ='Maccura' and Opportunity.AccountId =:con.Account__c )or(Opportunity.ExecutiveCompany__r.RecordType.DeveloperName !='Maccura' and Opportunity.ExecutiveCompany__c =:con.Account__c) ) ];
        for (Quote q : qlist) {
            qmbList.add(new QuoteMeasureBean(q, conId));
        }
           
       }
       */
    

        // 检索测算，审批通过的，同时业务机会阶段为招标且有赢单率小组
       String sql1 ='select Id, Name ,LastModifiedDate from Measure_Calculate__c where Status__c = \'审批成功\' and IsActive__c  = true and Opportunity__r.StageName = \'招标\''; 
         if(con.TerminalCustomer__c == null ){
           sql1 += ' and ((Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName =\'Maccura\' and Opportunity__r.AccountId =\''+con.Account__c+'\')or(Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName !=\'Maccura\' and Opportunity__r.ExecutiveCompany__c =\''+con.Account__c+'\'))'; 
        }else{
           sql1 += ' and ((Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName =\'Maccura\' and Opportunity__r.AccountId =\''+con.Account__c+'\' )or(Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName !=\'Maccura\' and Opportunity__r.ExecutiveCompany__c =\''+con.Account__c+'\')) and Opportunity__r.AccountId = \''+con.TerminalCustomer__c+'\''; 

        } 
        List<Measure_Calculate__c> mclist = Database.query(sql1);
      /* List<Measure_Calculate__c> mclist = [select Id, Name ,LastModifiedDate from Measure_Calculate__c where Status__c = '审批成功' and IsActive__c  = true and Opportunity__r.StageName = '招标' and 
                            ((Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName ='Maccura' and Opportunity__r.AccountId =:con.Account__c )or(Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName !='Maccura' and Opportunity__r.ExecutiveCompany__c =:con.Account__c))];*/
        for (Measure_Calculate__c mc : mclist) {
            qmbList.add(new QuoteMeasureBean(mc, conId));
        }

        System.debug('++++' + qmbList);
    }

    public class QuoteMeasureBean {
       public Quote q { get; set; }
        public Measure_Calculate__c mc { get; set; }
        // public Product__c p { get; set; }
        public String id { get; set; }
        public String name { get; set; }
        public Boolean chk { get; set; }
        public String type { get; set; }
        public String desc1 { get; set; }
        public String activeDate { get; set; }       // 审批通过日（审批通过后记录不能修改，暂时使用LastModifiedDate）
        public String contractName { get; set; }     // 关联的合同的名字
        public Boolean isThisContract { get; set; }  // 该报价是否已关联这个合同

        public Boolean isMCP {get;private set;}//是否为测算
        public String isAppendRegent {get;set;}//是否追加试剂

        public QuoteMeasureBean(Quote record, Id conId) {
            q = record;
            id = record.Id;
            name = record.Name;
            chk = false;
            type = '报价';
            desc1 = record.Type__c;
            activeDate = record.LastModifiedDate.format();
            contractName = record.Contract__c == null ? '' : record.Contract__r.Name;
            isThisContract = record.Contract__c == conId;
        }

        public QuoteMeasureBean(Measure_Calculate__c record, Id conId) {
            mc = record;
            id = record.Id;
            name = record.Name;
            chk = false;
            type = '测算';
            activeDate = record.LastModifiedDate.format();
            isMCP = true;


        }
        
            
    }

    
}